package cn.dapeng.linked;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.linked
 * @Description 把两个有序的链表合并成一个有序链表
 * @ClassName MergeLinkedNode
 * @Author xupenghong
 * @Date 2024/9/3 14:41
 * @Version 1.0.0
 */
public class MergeLinkedNode {

    /**
     * 把两个升序链表合并成一个升序链表
     *
     * @param h1
     * @param h2
     * @return
     */
    public static LinkedNode mergeTwoAscLinked(LinkedNode h1, LinkedNode h2) {
        if (h1 == null) {
            return h2;
        }
        if (h2 == null) {
            return h1;
        }
        LinkedNode head = h1.value > h2.value ? h2 : h1, next = head, pre;
        LinkedNode other = head == h1 ? h2 : h1;

        while (next.next != null) {
            if (next.next.value > other.value) {
                pre = next.next;
                next.next = other;
                other = pre;
            }
            next = next.next;
        }

        next.next = other;
        return head;
    }
}
